package com.itlong.cloud.controller.sdkV3.elevator;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.AppCallLiftSaveDTO;
import com.itlong.cloud.POJO.DTO.property.IotCloudElevatorStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.PO.DeviceElevatorFloorConfigPO;
import com.itlong.cloud.POJO.PO.DeviceElevatorInfoPO;
import com.itlong.cloud.POJO.VO.SDKMessageVO;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.sdk.CloudControllerButtonStatusVO;
import com.itlong.cloud.POJO.VO.sdk.CloudElevatorCallOutStatusVO;
import com.itlong.cloud.POJO.VO.sdk.CloudElevatorSDKGetByDeviceUniqueVO;
import com.itlong.cloud.POJO.VO.sdk.SDKDeviceCloudControllerInfoVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudElevarotErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudElevatorSDKServerCloudServiceClient;
import com.itlong.cloud.iottp.IIotSDKServiceClient;
import com.itlong.cloud.iottp.IIotServerServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.sdk.ICloudElevatorSDKServerProjectServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <desc>
 * 云电梯SDK服务端云端对旺龙云端控制器
 * </desc>
 *
 * @createDate 2018/12/27
 */
@RestController
@RequestMapping("/sdkv3/cloud/elevator/ctl")
public class SDKCloudElevatorCTLController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(SDKCloudElevatorCTLController.class);

    @Autowired
    private ICloudElevatorSDKServerCloudServiceClient iCloudElevatorSDKServerCloudServiceClient;

    @Autowired
    private ICloudElevatorSDKServerProjectServiceClient iCloudElevatorSDKServerProjectServiceClient;

    @Autowired
    private IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IIotServerServiceClient iIotServerServiceClient;

    @Autowired
    private IIotSDKServiceClient iIotSDKServiceClient;


    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    /**
     * <desc>
     * 查询项目下电梯设备唯一码列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/27
     */
    @UnAuthAccessRequired
    public Object getElevatorKey(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
        cloudElevatorSDKServerGetElevatorPageDTO.setAppId(dto.getAppId());
        cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(dto.getProjectId());
        LOG.info("======getElevatorKey查询项目下电梯设备唯一码列表=====ctl=========入参=============>{}", null == dto ? "" : dto.toString());
        List<String> deviceArr = iCloudElevatorSDKServerCloudServiceClient.getElevatorPage(cloudElevatorSDKServerGetElevatorPageDTO);
        LOG.info("======getElevatorKey查询项目下电梯设备唯一码列表======ctl=======出参=============>{}", null == deviceArr ? "" : deviceArr.toString());
        return deviceArr;
    }

    /**
     * <desc>
     * 根据设备唯一码查询电梯信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/12/28
     */
    @UnAuthAccessRequired
    public Object getElevatorInfo(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = new CloudElevatorSDKGetByDeviceUniqueDTO();
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppId(dto.getAppId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setAppSecret(dto.getAppSecret());
        cloudElevatorSDKGetByDeviceUniqueDTO.setProjectId(dto.getProjectId());
        cloudElevatorSDKGetByDeviceUniqueDTO.setDeviceUnique(dto.getDeviceUnique());
        LOG.info("======getElevatorInfo根据设备唯一码查询电梯信息======ctl=====入参================>{}", null == dto ? "" : dto.toString());
        //设备权限验证
        int result = this.checkDeveloperAuth(dto);
        if (result == 1) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(), "");
        }

        List<CloudElevatorSDKGetByDeviceUniqueVO> deviceArr = iCloudElevatorSDKServerCloudServiceClient.getElevatorInfo(cloudElevatorSDKGetByDeviceUniqueDTO);
        LOG.info("======getElevatorInfo根据设备唯一码查询电梯信息====ctl=====出参==================>{}", null == deviceArr ? "" : deviceArr.toString());
        return deviceArr;
    }

    /**
     * <desc>
     * 设置信息变更路由和状态上报路由
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/12/27
     */
    @ResponseBody
    @PostMapping("/setUrl")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SET_INFO_MODIFY_URL_LOG_DESC)
    public Object setUrl() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudElevatorSDKServerSetUrlDTO cloudElevatorSDKServerSetUrlDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKServerSetUrlDTO.class, request);
            cloudElevatorSDKServerSetUrlDTO.setAppId(request.getAttribute("appId").toString());
            iCloudElevatorSDKServerProjectServiceClient.setUrl(cloudElevatorSDKServerSetUrlDTO);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKServerSetUrlDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                            request.getAttribute("appSecret").toString()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_setUrl】设置信息变更路由和状态上报路由失败", e);
        }
    }

    /**
     * <desc>
     * 发送开门关门指令
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2018/12/28
     */
    @ResponseBody
    @PostMapping("/sendOpenAndCloseDoor")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SEND_OPEN_CLOSE_DOOR_LOG_DESC)
    public Object sendOpenAndCloseDoor() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO cloudElevatorSDKServerSendCommandDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            cloudElevatorSDKServerSendCommandDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKServerSendCommandDTO.setAppSecret(request.getAttribute("appSecret").toString());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKServerSendCommandDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            LOG.info("======发送开门关门指令==ctl=========入参================>{}", null == cloudElevatorSDKServerSendCommandDTO ? "" : cloudElevatorSDKServerSendCommandDTO.toString());

            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(cloudElevatorSDKServerSendCommandDTO.getProjectId(), cloudElevatorSDKServerSendCommandDTO.getAppId());
            Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            Integer robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
            cloudElevatorSDKServerSendCommandDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            cloudElevatorSDKServerSendCommandDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);

            //设备权限验证
            int result = this.checkDeveloperAuth(cloudElevatorSDKServerSendCommandDTO);
            String responseTimestamp = new Date().getTime() + "";
            if (result == 1) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }
            Integer effectiveTime = cloudElevatorSDKServerSendCommandDTO.getEffectiveTime();
            if (effectiveTime == null) {
                effectiveTime = 1;
            }
            if (effectiveTime < 0 || effectiveTime > 99) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_EFFECTIVE_TIME_OUT_ERR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKServerSendCommandDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKServerSendCommandDTO.getProjectId());
            List<String> deviceUniques = iCloudElevatorSDKServerCloudServiceClient.getElevatorPage(cloudElevatorSDKServerGetElevatorPageDTO);
            if (deviceUniques == null || deviceUniques.isEmpty() || !deviceUniques.contains(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            //云电梯设备判断,云机器人版不支持云端功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique());
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, "");
            }

            if (cloudElevatorSDKServerSendCommandDTO.getType() == 1) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.OPEN.getType(), effectiveTime, CallElevatorSourceTypeEnum.APP.getType(), null, null, null, 1, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, "");
            }
            if (cloudElevatorSDKServerSendCommandDTO.getType() == 2) {
                iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(),
                        CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                        null, null, null, CloudElevatorCallTypeEnum.CLOSE.getType(), effectiveTime, CallElevatorSourceTypeEnum.APP.getType(), null, null, null, 1, cloudElevatorSDKServerSendCommandDTO.getUpDown(), null, "");
            }
            //判断电梯当前状态是否是开门，如果是开门则返回成功，否则返回失败
            boolean isOpen = false;
            int count = 0;
            while (count < 6) {
                Thread.sleep(500);
                IotCloudElevatorStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ELEVATOR_STATE_CACHE +
                        cloudElevatorSDKServerSendCommandDTO.getDeviceUnique()), IotCloudElevatorStateDTO.class);
                if (dto != null && StringUtils.isNotBlank(dto.getFrontDoor()) && (dto.getFrontDoor().equals("1") ||
                        dto.getFrontDoor().equals("3") || dto.getFrontDoor().equals("4"))) {
                    isOpen = true;
                    break;
                } else {
                    //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                    iAppDeviceServiceClient.getCloudElevatorState(cloudElevatorSDKServerSendCommandDTO.getDeviceUnique(), "");
                }
                count++;
            }
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isOpen", isOpen + "");

            Map<String, Object> signMap = new HashMap<>();
            signMap.put("data", new JSONObject(resultMap));//签名使用json格式内容进行
            LOG.info("======发送开门关门指令======ctl======出参================>{}", null == signMap ? "" : signMap.toString());

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), cloudElevatorSDKServerSendCommandDTO.getRequestId(),
                    responseTimestamp, Md5EncryptUtil.getSDKV2Md5(signMap, cloudElevatorSDKServerSendCommandDTO.getRequestId(), responseTimestamp, cloudElevatorSDKServerSendCommandDTO.getAppSecret()), resultMap);
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_服务端】发送开门关门指令失败", e);
        }
    }

    /**
     * <desc>
     * 公共参数权限判断
     * <desc/>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/09/18
     */
    @UnAuthAccessRequired
    public Object publicParamCheck(CloudDeviceSDKDTO dto) throws Exception {
        //设备权限验证
        int result = this.checkDeveloperAuth(dto);
        if (result == 1) {
            return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), dto.getRequestId(), "", "");
        }
        return null;
    }

    /**
     * <desc>
     * 打开关闭上报状态
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @ResponseBody
    @PostMapping("/openOrCloseStateReport")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_OPEN_OR_CLOSE_DESC)
    public Object openOrCloseStateReport() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudElevatorSDKStateReportDTO cloudElevatorSDKStateReportDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKStateReportDTO.class, request);
            cloudElevatorSDKStateReportDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKStateReportDTO.setAppSecret(request.getAttribute("appSecret").toString());
            LOG.info("======打开关闭上报状态===ctl=========出参================>{}", null == cloudElevatorSDKStateReportDTO ? "" : cloudElevatorSDKStateReportDTO.toString());

            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKStateReportDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            if (StringUtils.isEmpty(cloudElevatorSDKStateReportDTO.getProjectId())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_EFFECTIVE_TIME_OUT_ERR.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp, "");
            }
            //判断是否有url等参数
            Map<String, Object> map = iCloudElevatorSDKServerCloudServiceClient.getReportInfo(cloudElevatorSDKStateReportDTO.getAppId(),
                    cloudElevatorSDKStateReportDTO.getAppSecret(), cloudElevatorSDKStateReportDTO.getProjectId());
            if (map == null || map.get("url") == null) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.CLOUD_URL_ERROR.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp, "");
            }
            //打开关闭上报状态
            iCloudElevatorSDKServerCloudServiceClient.setOpenOrCloseStateReport(cloudElevatorSDKStateReportDTO);
            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), request.getAttribute("requestId").toString(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), request.getAttribute("requestId").toString(), responseTimestamp,
                            request.getAttribute("appSecret").toString()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_openOrCloseStateReportv】打开关闭上报状态异常", e);
        }
    }

    /**
     * <desc>
     * 预约电梯
     * <desc/>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2019-01-03
     */
    @RequestMapping(value = "/callElevator", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SEVER_CALL_ELEVATOR)
    @ResponseBody
    public Object callElevator() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        try {
            CloudDeviceSDKDTO cloudElevatorSDKCallElevatorDTO =
                    HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
            cloudElevatorSDKCallElevatorDTO.setAppId(request.getAttribute("appId").toString());
            cloudElevatorSDKCallElevatorDTO.setAppSecret(request.getAttribute("appSecret").toString());
            LOG.info("======callElevator预约电梯CTL============入参================>{}", null == cloudElevatorSDKCallElevatorDTO ? "" : cloudElevatorSDKCallElevatorDTO.toString());

            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark", cloudElevatorSDKCallElevatorDTO.toString());
            request.setAttribute("portType", LogDescConstant.SDK_CLOUD_ELEVATOR_TYPE_LOG_DESC);
            String responseTimestamp = new Date().getTime() + "";
            if (StringUtils.isEmpty(cloudElevatorSDKCallElevatorDTO.getProjectId())) {
                return new SDKMessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            Map<String, Object> AuthStatus = iOperateProjectServiceClient.getRobotGoProjectWhitelistAndDeviceAuthStatusByUserId(cloudElevatorSDKCallElevatorDTO.getProjectId(), cloudElevatorSDKCallElevatorDTO.getAppId());
            Integer robotWhiteListAuthStatus = Integer.parseInt(AuthStatus.get("robotWhiteListAuthStatus") + "");
            Integer robotDeviceAuthStatus = Integer.parseInt(AuthStatus.get("robotDeviceAuthStatus") + "");
            cloudElevatorSDKCallElevatorDTO.setRobotWhiteListAuthStatus(robotWhiteListAuthStatus);
            cloudElevatorSDKCallElevatorDTO.setRobotDeviceAuthStatus(robotDeviceAuthStatus);
            //设备权限验证
            int result = this.checkDeveloperAuth(cloudElevatorSDKCallElevatorDTO);
            if (result == 1) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            //云电梯设备判断,云机器人版不支持云端功能
            DeviceElevatorInfoPO po = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            if (po != null && po.getDeviceAttributes() != null && po.getDeviceAttributes() == 2) {//设备属性配置 ：1标准 2云机器人 3全功能
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_NOT_SUPPORT_THIS_FUNCTIONS.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            //获取真实楼层
            Map<String, Object> floor = iCloudElevatorSDKServerCloudServiceClient.getFloorNumByLogicFloor(cloudElevatorSDKCallElevatorDTO.getFromFloor(),
                    cloudElevatorSDKCallElevatorDTO.getToFloor(), cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            if (floor == null || floor.get("goFloor") == null || floor.get("fromFloor") == null) {
                return new SDKMessageVO(CloudElevarotErrorCodeEnum.CLOUD_FLOOR_ERROR.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            CloudElevatorVO vo = iAppDeviceServiceClient.getCallElevatorInfo(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(vo.getIotProductKey(), cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp, "");
            }
            /// TODO: 2020/7/17  Wenchao.L ：预约呼梯的类型是固定的,应该是要有个单独的云端API呼梯的类型

            //调用IOT呼梯
            iAppDeviceServiceClient.cloudElevatorCall(cloudElevatorSDKCallElevatorDTO.getDeviceUnique(),
                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(),
                    floor.get("goFloor").toString(), floor.get("fromFloor").toString(), cloudElevatorSDKCallElevatorDTO.getFloor(),
                    CloudElevatorCallTypeEnum.OUT.getType(), null, CallElevatorSourceTypeEnum.APP.getType(), null, null,
                    cloudElevatorSDKCallElevatorDTO.getCtrElevator(), 1, cloudElevatorSDKCallElevatorDTO.getUpDown(), null, "");


            //装配呼梯记录对象
            AppCallLiftSaveDTO saveDTO = new AppCallLiftSaveDTO();
            saveDTO.setDeviceUnique(cloudElevatorSDKCallElevatorDTO.getDeviceUnique());
            saveDTO.setFromFloor(floor.get("fromNaturalFloor").toString());
            saveDTO.setToFloor(floor.get("goNaturalFloor").toString());
            saveDTO.setProjectId(cloudElevatorSDKCallElevatorDTO.getProjectId());
            saveDTO.setSource(CallElevatorRecordSourceEnum.CLOUD.getType());
            saveDTO.setUserId(cloudElevatorSDKCallElevatorDTO.getAppId());
            iAppHomeServiceClient.saveCallLiftRecord(saveDTO);

            return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp,
                    Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), cloudElevatorSDKCallElevatorDTO.getRequestId(), responseTimestamp,
                            cloudElevatorSDKCallElevatorDTO.getAppSecret()));
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_云电梯_callElevator】预约电梯异常", e);
        }
    }

    /**
     * <desc>
     * 开发者权限判断
     * <desc/>
     *
     * @param dto
     * @return
     * @author Qiang.S
     * @createDate 2019-09-18
     */
    @UnAuthAccessRequired
    private int checkDeveloperAuth(CloudDeviceSDKDTO dto) throws Exception {
        CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
        cloudElevatorSDKServerGetElevatorPageDTO.setAppId(dto.getAppId());
        cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(dto.getProjectId());
        List<String> deviceUniques = iCloudElevatorSDKServerCloudServiceClient.getElevatorPage(cloudElevatorSDKServerGetElevatorPageDTO);
        List<String> deviceUniqueParams = StringHandlerUtil.splitStringList(dto.getDeviceUnique());
        for (String deviceUniqueParam : deviceUniqueParams) {
            if (deviceUniques == null || !deviceUniques.contains(deviceUniqueParam)) {
                return 1;
            }
        }
        return 0;
    }

    /**
     * <desc>
     * 外呼状态
     * <desc/>
     *
     * @return
     * @author chaoshuai
     * @createDate 2020/08/05
     */
    @RequestMapping(value = "/getOutCallStatus", method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SEVER_CALL_ELEVATOR)
    @ResponseBody
    public Object getOutCallStatus(CloudDeviceSDKDTO dto) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        dto = HttpProtocolUtil.parseRequestParamToDTO(CloudDeviceSDKDTO.class, request);
        LOG.info("======getOutCallStatus外呼状态====ctl========入参================>{}", null == dto ? "" : dto.toString());

        List<CloudElevatorCallOutStatusVO> cloudElevatorCallOutStatusVOS = new ArrayList<>();
        //String elevatorDeviceUniques = iCloudElevatorSDKServerCloudServiceClient.getDeviceUniqueByControllerDeviceUnique(dto.getDeviceUnique());
        String elevatorDeviceUniques = iCloudElevatorSDKServerCloudServiceClient.getDeviceUniqueBy(dto.getDeviceUnique());
        if (StringUtils.isBlank(elevatorDeviceUniques)) {
            return new SDKMessageVO(AppErrorCodeEnum.DEVICE_NOT_HUAWEI_IOT.getErrorCode(), dto.getRequestId(), System.currentTimeMillis() + "", "");
        }
        String elevatorDeviceUnique = StringHandlerUtil.splitString(elevatorDeviceUniques)[0];
        try {
            //获取电梯信息
            DeviceElevatorInfoPO deviceElevatorInfoPO = iCloudElevatorSDKServerCloudServiceClient.getElevatorByDeviceUnique(elevatorDeviceUnique);
            if (null == deviceElevatorInfoPO) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_DATA_ERROR.getErrorCode(), dto.getRequestId(), System.currentTimeMillis() + "", "");
            }
            //获取楼层数据参数
            Map<String, Object> params = new HashMap(16);
            params.put("floorNo", deviceElevatorInfoPO.getFloorNo());
            params.put("floorNoMax", deviceElevatorInfoPO.getFloorNoMax());
            params.put("deviceUnique", elevatorDeviceUnique);
            //获取楼层信息
            List<DeviceElevatorFloorConfigPO> deviceElevatorFloorConfigPOs = iCloudElevatorSDKServerCloudServiceClient.getFloorInfoByMap(params);
            for (DeviceElevatorFloorConfigPO deviceElevatorFloorConfigPO : deviceElevatorFloorConfigPOs) {
                CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO = new CloudElevatorCallOutStatusVO();
                cloudElevatorCallOutStatusVO.setNaturalFloor(deviceElevatorFloorConfigPO.getNaturalFloor());
                cloudElevatorCallOutStatusVO.setLogicalFloor(deviceElevatorFloorConfigPO.getLogicalFloor());
                cloudElevatorCallOutStatusVO.setFloorNum(deviceElevatorFloorConfigPO.getFloorNum());
                cloudElevatorCallOutStatusVOS.add(cloudElevatorCallOutStatusVO);
            }

            //获取云控制器信息
            SDKDeviceCloudControllerInfoVO deviceCloudControllerInfoVO = iCloudElevatorSDKServerCloudServiceClient.getDeviceCloudControllerInfo(dto.getDeviceUnique());
            if (null == deviceCloudControllerInfoVO || StringUtils.isBlank(deviceCloudControllerInfoVO.getHuaweiIotId())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_DEVICE_DATA_ERROR.getErrorCode(), dto.getRequestId(), System.currentTimeMillis() + "", "");
            }
            //判断当前设备是否在线，如不在线返回失败
            String isOnline = iIotServerServiceClient.batchGetDeviceState(deviceCloudControllerInfoVO.getIotProductKey(), deviceCloudControllerInfoVO.getDeviceUnique());
            //判断设备是否在线
            if (isOnline == null || (isOnline != null && !isOnline.equals(IotDeviceStatusEnum.ONLINE.getType()))) {
                return new SDKMessageVO(AppErrorCodeEnum.CLOUD_ELEVATOR_OUT_LINE.getErrorCode(), dto.getRequestId(), System.currentTimeMillis() + "", "");
            }

            //默认全部楼层为未安装
            for (CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO : cloudElevatorCallOutStatusVOS) {
                cloudElevatorCallOutStatusVO.setUp(-1);
                cloudElevatorCallOutStatusVO.setDown(-1);

            }
            //上行楼层已安装赋值
            List<String> upFloors = Arrays.asList(StringHandlerUtil.splitString(deviceCloudControllerInfoVO.getUpFloor()));
            for (CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO : cloudElevatorCallOutStatusVOS) {
                boolean b = upFloors.stream().anyMatch(upFloor -> upFloor.equals(cloudElevatorCallOutStatusVO.getNaturalFloor()));
                if (b) {
                    cloudElevatorCallOutStatusVO.setUp(0);
                }

            }
            //下行楼层已安装赋值
            List<String> downFloors = Arrays.asList(StringHandlerUtil.splitString(deviceCloudControllerInfoVO.getDownFloor()));
            for (CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO : cloudElevatorCallOutStatusVOS) {
                boolean b = downFloors.stream().anyMatch(downFloor -> downFloor.equals(cloudElevatorCallOutStatusVO.getNaturalFloor()));
                if (b) {
                    cloudElevatorCallOutStatusVO.setDown(0);
                }

            }

            //获取按键状态
            CloudControllerButtonStatusVO cloudControllerButtonStatusVO = iIotSDKServiceClient.getButtonStatus(deviceCloudControllerInfoVO.getHuaweiIotId());
            //iot状态码 0 成功 非0失败
            Integer iotSuccess = 0;
            if (!iotSuccess.equals(cloudControllerButtonStatusVO.getMsgCode())) {
                return new SDKMessageVO(SDKErrorCodeEnum.SDK_IOT_DATA_ERROR.getErrorCode(), dto.getRequestId(), System.currentTimeMillis() + "", "");
            }
            List<String> ups = Arrays.asList(StringHandlerUtil.splitString(cloudControllerButtonStatusVO.getUp()));
            for (CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO : cloudElevatorCallOutStatusVOS) {
                boolean b = ups.stream().anyMatch(up -> up.equals(cloudElevatorCallOutStatusVO.getLogicalFloor()));
                if (b) {
                    cloudElevatorCallOutStatusVO.setUp(1);
                }
            }
            List<String> downs = Arrays.asList(StringHandlerUtil.splitString(cloudControllerButtonStatusVO.getDown()));
            for (CloudElevatorCallOutStatusVO cloudElevatorCallOutStatusVO : cloudElevatorCallOutStatusVOS) {
                boolean b = downs.stream().anyMatch(down -> down.equals(cloudElevatorCallOutStatusVO.getLogicalFloor()));
                if (b) {
                    cloudElevatorCallOutStatusVO.setDown(1);
                }
            }

            Collections.sort(cloudElevatorCallOutStatusVOS, new Comparator<CloudElevatorCallOutStatusVO>() {
                @Override
                public int compare(CloudElevatorCallOutStatusVO p1, CloudElevatorCallOutStatusVO p2) {
                    return Integer.valueOf(p1.getFloorNum()) - Integer.valueOf(p2.getFloorNum());
                }
            });
        } catch (Exception e) {
            request.setAttribute("exception", e.toString());
            throw new DataAccessException("【SDK_外呼状态检测】获取外呼状态败", e);
        }
        return new SDKMessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), dto.getRequestId(), dto.getResponseTimestamp(),
                Md5EncryptUtil.getSDKV2Md5(new HashMap<>(), dto.getRequestId(), dto.getResponseTimestamp(), dto.getAppSecret()), cloudElevatorCallOutStatusVOS);
    }


}
